<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import { NButton, type NTree, type TreeOption } from 'naive-ui';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
import { enableStatusOptions } from '@/constants/business';
import { roleGetMenuIdById, roleMenuTree, roleSave, roleUpdate } from '@/service/api/sys-role';

defineOptions({
  name: 'RoleOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.SystemManage.Role | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: $t('page.manage.role.addRole'),
    edit: $t('page.manage.role.editRole')
  };
  return titles[props.operateType];
});

type Model = Pick<Api.SystemManage.Role, 'id' | 'name' | 'status'> & { menuIds: Array<string> };

const model: Model = reactive(createDefaultModel());

const menuVO = ref<{ menuTree: TreeOption[]; allMenuIds: string[] }>({
  menuTree: [],
  allMenuIds: []
});

const menuTreeRef = ref<InstanceType<typeof NTree>>();

function createDefaultModel(): Model {
  return {
    id: '',
    name: '',
    status: null,
    menuIds: []
  };
}

type RuleKey = Exclude<keyof Model, 'remark' | 'id' | 'menuIds'>;

const rules = computed<Record<RuleKey, App.Global.FormRule>>(() => {
  const { defaultRequiredRule } = useFormRules();

  return {
    name: defaultRequiredRule,
    status: defaultRequiredRule
  };
});

const isEdit = computed(() => props.operateType === 'edit');

function handleInitModel() {
  Object.assign(model, createDefaultModel());
  roleMenuTree().then(({ data, error }) => {
    if (!error) {
      menuVO.value = data;
      menuVO.value.allMenuIds = data.allMenuIds;
      menuVO.value.menuTree = data.menuTree;
    }
  });
  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
    roleGetMenuIdById({ id: props.rowData.id }).then(({ error, data }) => {
      if (!error) {
        model.menuIds = data;
      }
    });
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();
  if (model.menuIds.length === 0) {
    window.$message?.warning('角色菜单不可为空');
    return;
  }
  if (isEdit.value) {
    const { error } = await roleUpdate(model);
    if (!error) {
      window.$message?.success($t('common.updateSuccess'));
    }
  } else {
    const { error } = await roleSave(model);
    if (!error) {
      window.$message?.success($t('common.addSuccess'));
    }
  }

  closeDrawer();
  emit('submitted');
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" display-directive="show" :width="360">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NFormItem :label="$t('page.manage.role.roleName')" path="name">
          <NInput v-model:value="model.name" :placeholder="$t('page.manage.role.form.roleName')" />
        </NFormItem>

        <NFormItem :label="$t('page.manage.role.roleStatus')" path="status">
          <NRadioGroup v-model:value="model.status">
            <NRadio v-for="item in enableStatusOptions" :key="item.value" :value="item.value" :label="$t(item.label)" />
          </NRadioGroup>
        </NFormItem>
      </NForm>
      <NFormItem path="menuIds">
        <template #label>
          <div class="flex items-center gap-2">
            <div>权限</div>
            <div class="flex gap-2">
              <NButton
                type="info"
                @click="
                  () => {
                    model.menuIds = menuVO.allMenuIds;
                  }
                "
              >
                全选
              </NButton>
              <NButton
                type="warning"
                @click="
                  () => {
                    model.menuIds = [];
                  }
                "
              >
                清空
              </NButton>
            </div>
          </div>
        </template>
        <NTree
          ref="menuTreeRef"
          v-model:checked-keys="model.menuIds"
          :data="menuVO.menuTree"
          multiple
          :selectable="false"
          block-node
          default-expand-all
          check-on-click
          checkable
        />
      </NFormItem>

      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
